Terraform 是一個用於管理基礎設施代碼 (Infrastructure as Code,IaC) 的工具,它允許你通過定義和配置基礎設施來自動化資源的創建和管理。Terraform 使用的配置語言被稱為 HCL (HashiCorp Configuration Language),它是一種專為描述基礎設施的語言。
宣告性語言 (Declarative Language): HCL 是一種宣告性的語言,這意味著你描述你想要的狀態,而不是指定詳細的步驟。Terraform 將根據你的描述來決定如何創建和管理基礎設施。
資源塊 (Resource Blocks): 在 HCL 中,你使用資源塊來定義不同類型的基礎設施資源。每個資源塊描述了一個特定資源的屬性和配置。
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
variable "instance_names" {
description = "A map of instance names"
type = map(string)
default = {
"web" = "t2.micro"
"app" = "t2.small"
"db" = "t2.medium"
}
}
resource "aws_instance" "example" {
for_each = var.instance_names
ami = "ami-0c55b159cbfafe1f0"
instance_type = each.value
tags = {
Name = each.key
}
}
variable "instance_names" {
description = "A map of instance names"
type = map(string)
default = {
"web" = "t2.micro"
"app" = "t2.small"
"db" = "t2.medium"
}
}
resource "aws_instance" "example" {
for_each = var.instance_names
ami = "ami-0c55b159cbfafe1f0"
instance_type = each.value
tags = {
Name = each.key
}
}
data "aws_ami" "selected_ami" {
most_recent = true
filter {
name = "name"
values = ["amzn2-ami-hvm-*-x86_64-ebs"]
}
filter {
name = "root-device-type"
values = ["ebs"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
owners = ["amazon"
}
resource "aws_route53_zone" "r53zone" {
# checkov:skip=CKV2_AWS_38: Need to check DNSSEC later
# checkov:skip=CKV2_AWS_39: We don't want to enable logging at this moment
name = var.domain_name
dynamic "vpc" {
for_each = var.vpcs
content {
vpc_id = vpc.value["vpc_id"]
vpc_region = vpc.value["vpc_region"]
}
}
tags = { for tag in var.tags : tag.key => tag.value }
}
接下來,下一篇將介紹 HCL 常用到的函式。